import { asyncRouters, commonRouters } from '@/router'

export function filterAsyncRoutes(routes) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children)
    }
    if (tmp.hidden && typeof tmp.hidden !== 'boolean') {
      tmp.hidden = true;
    }
    res.push(tmp)
  })

  return res
}

const router = {
  state: {
    routers: commonRouters,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = commonRouters.concat(routers);
    }
  },
  getters: {
    getAddRouters: state => state.addRouters,
    getRouters: () => filterAsyncRoutes(asyncRouters)
  },
  actions: {
    GenerateRoutes ({ commit }) {
      return new Promise(resolve => {
        const accessedRouters = filterAsyncRoutes(asyncRouters)

        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default router
